package com.holy.sh.module_base_mvp.base.app;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.support.multidex.MultiDexApplication;
import android.util.Base64;
import android.util.Log;

import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.holy.sh.module_base_mvp.BuildConfig;
import com.holy.sh.module_base_mvp.constants.ConstantsApi;

import com.holy.sh.module_base_mvp.helper.SpfHelper;
import com.holy.sh.module_base_mvp.helper.gson.NullStringToEmptyAdapterFactory;
import com.holy.sh.module_base_mvp.utils.ToastUtil;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.internal.Utils;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Holy Email :victorhhl@163.com
 * Create by Holy on 2019/5/27
 * Description :
 */
public class BaseApp extends MultiDexApplication {
    private static volatile OkHttpClient okHttpClient;
    public static volatile Context context;
    public static volatile BaseApp instence;
    private static volatile Gson gson = null;
    private SharedPreferences sharedPreferences;
    private static volatile SpfHelper spfHelper;

    @Override
    public void onCreate() {
        super.onCreate();
        context=this;
        instence=this;
        ToastUtil.initialize(this);
        sharedPreferences = getSharedPreferences("gomro_resident", MODE_PRIVATE);

    }



    /**
     * Gson 单例
     */
    public Gson getGson() {
        if (gson == null) {
            synchronized (Gson.class) {
                if (gson == null) {
                    gson = new GsonBuilder()
                            .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory())
                            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                            .create();
                }
            }
        }
        return gson;
    }

    /**
     * 获取对象
     *
     * @param context
     * @param key
     * @return
     */
    public Object getBean(Context context, String key) {
        Object obj = null;
        try {
            String base64 = sharedPreferences.getString(key, "");
            Log.i("1606", "base64" + base64);
            if (base64.equals("")) {
                return null;
            }
            byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
            ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 保存对象
     *
     * @param context
     * @param key     关键字
     * @param obj
     */
    public void putBean(Context context, String key, Object obj) {
        if (obj instanceof Serializable) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
                String string64 = new String(Base64.encode(baos.toByteArray(),
                        0));
                Log.i("1606", "String64" + string64);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(key, string64);
                editor.commit();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new IllegalArgumentException(
                    "the obj must implement Serializble");
        }
    }

    /**
     * SpfHelper 单例
     */
    public SpfHelper getSpfHelper() {
        if (spfHelper == null) {
            synchronized (SpfHelper.class) {
                if (spfHelper == null) {
                    spfHelper = new SpfHelper(this, ConstantsApi.SP_NAME);
                }
            }
        }
        return spfHelper;
    }


    /**
     * OkHttp
     */
    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (OkHttpClient.class) {
                if (null == okHttpClient) {

                    OkHttpClient.Builder builder = new OkHttpClient.Builder();

                    if (BuildConfig.DEBUG) {
                        Stetho.initializeWithDefaults(instence);
                        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                        builder.addNetworkInterceptor(new StethoInterceptor());  //添加facebook的拦截器
                        builder.addInterceptor(interceptor);
                       /* builder.addInterceptor(chain -> {
                            Request request = chain.request();
                           *//* RequestBody requestBody = request.body();
                            Buffer buffer1 = new Buffer();
                            requestBody.writeTo(buffer1);
                            String bodyParams = buffer1.readString(Charset.forName("UTF-8"));
                            bodyParams = bodyParams.replaceAll("&", "\n");
                           // bodyParams = URLDecoder.decode(bodyParams, "utf-8");
                            Logger.d("请求参数\n" + bodyParams);*//*
                            Response response = chain.proceed(request);
                            ResponseBody body = response.body();
                            BufferedSource source = body.source();
                            source.request(Long.MAX_VALUE); // Buffer the entire body.
                            Charset charset = body.contentType().charset(Charset.forName("UTF-8"));
                            Buffer buffer = source.buffer();
                            String json = buffer.clone().readString(charset);
                            Request request1 = response.request();
                            RequestBody requestBody = request1.body();

                            Buffer buffer1 = new Buffer();
                            if (requestBody!=null){
                                requestBody.writeTo(buffer1);
                            }
                            String bodyParams = buffer1.readString(Charset.forName("UTF-8"));
                            bodyParams = bodyParams.replaceAll("&", "\n");
                            bodyParams = URLDecoder.decode(bodyParams, "utf-8");
                            Logger.d("请求参数\n" + bodyParams);
                            Logger.json(json);
                            return response;
                        });*/
                    }

                    try {
                        //原来的证书
                        //trustManagerForCertificates(builder, get().getAssets().open("public.pem"));
                        //2017.12.8号换的ssl证书 双12之后上线
                        //trustManagerForCertificates(builder, get().getAssets().open("51xpx-com-cn-certificate.pem"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //   File cacheFile = new File(get().getCacheDir(), "httpCache");
                    //  Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
                    //   builder.cache(cache);

                    builder.connectTimeout(20, TimeUnit.SECONDS);
                    builder.writeTimeout(20, TimeUnit.SECONDS);
                    builder.readTimeout(30, TimeUnit.SECONDS);
                    okHttpClient = builder.build();
                }
            }
        }
        return okHttpClient;
    }

}
